import React, { useState, useEffect } from 'react';
import { Box } from '@mui/material';
import GridLayout from '../../general/GridLayout';
import ExpansionPanel from '../../general/ExpansionPanel';
import RulePath from '../../general/RulePath';
import Utils from '../../../utils/Utils';
import NetPyNENewPlot from './NetPyNENewPlot';
import NetPyNEPlotThumbnail from './NetPyNEPlotThumbnail';

// Import plot type components (placeholders for now - will be migrated separately)
import PlotRaster from './plotTypes/PlotRaster';
import PlotSpikeHist from './plotTypes/PlotSpikeHist';
import PlotSpikeStats from './plotTypes/PlotSpikeStats';
import PlotRatePSD from './plotTypes/PlotRatePSD';
import PlotTraces from './plotTypes/PlotTraces';
import PlotLFP from './plotTypes/PlotLFP';
import PlotConn from './plotTypes/PlotConn';
import Plot2Dnet from './plotTypes/Plot2Dnet';
import PlotGranger from './plotTypes/PlotGranger';
import PlotRateSpectrogram from './plotTypes/PlotRateSpectrogram';

interface NetPyNEPlotsProps {
  value?: Record<string, any>;
  model?: string;
  updateCards?: () => void;
  commands?: any[];
  [key: string]: any;
}

interface NetPyNEPlotsState {
  selectedPlot?: string;
  page: string;
}

/**
 * NetPyNEPlots Component
 * Manages the list of plot configurations
 */
const NetPyNEPlots: React.FC<NetPyNEPlotsProps> = ({
  value: propValue,
  model: propModel,
  updateCards,
  commands,
  ...otherProps
}) => {
  const [state, setState] = useState<NetPyNEPlotsState>({
    selectedPlot: undefined,
    page: 'main',
  });

  useEffect(() => {
    // Handle commands updates if needed
  }, [commands]);

  const selectPlot = (plot: string): void => {
    setState((prev) => ({ ...prev, selectedPlot: plot }));
  };

  const handleNewPlot = (plot: string): void => {
    let model = propValue ? { ...propValue } : {};
    
    if (model === undefined) {
      model = {};
    }
    
    model[plot] = true;

    Utils.evalPythonMessage('netpyne_geppetto.getAvailablePlots', [])
      .then((response: string[]) => {
        if (response.includes(plot)) {
          let include: any = {};
          if (plot === 'plotLFP') {
            include = { electrodes: ['all'] };
          } else if (plot === 'granger') {
            include = {
              cells1: ['allCells'],
              cells2: ['allCells'],
            };
          } else {
            include = { include: ['all'] };
          }
          Utils.execPythonMessage(
            `netpyne_geppetto.simConfig.analysis['${plot}'] = ${JSON.stringify(include)}`
          );
        }
      });

    setState((prev) => ({
      ...prev,
      selectedPlot: plot,
    }));
  };

  // Generate plot thumbnails
  const plots: React.ReactNode[] = [];
  let selectedPlotComponent: React.ReactNode = null;

  if (propValue !== undefined && typeof propValue === 'object') {
    for (const plotName in propValue) {
      plots.push(
        <NetPyNEPlotThumbnail
          key={plotName}
          name={plotName}
          selected={plotName === state.selectedPlot}
          handleClick={selectPlot}
        />
      );
    }

    // Render the selected plot component
    switch (state.selectedPlot) {
      case 'iplotRaster':
        selectedPlotComponent = <PlotRaster />;
        break;
      case 'iplotSpikeHist':
        selectedPlotComponent = <PlotSpikeHist />;
        break;
      case 'iplotSpikeStats':
        selectedPlotComponent = <PlotSpikeStats />;
        break;
      case 'iplotRatePSD':
        selectedPlotComponent = <PlotRatePSD />;
        break;
      case 'iplotTraces':
        selectedPlotComponent = <PlotTraces />;
        break;
      case 'iplotLFP':
        selectedPlotComponent = <PlotLFP />;
        break;
      case 'iplotConn':
        selectedPlotComponent = <PlotConn />;
        break;
      case 'iplot2Dnet':
        selectedPlotComponent = <Plot2Dnet />;
        break;
      case 'granger':
        selectedPlotComponent = <PlotGranger />;
        break;
      case 'plotRateSpectrogram':
        selectedPlotComponent = <PlotRateSpectrogram />;
        break;
      default:
        selectedPlotComponent = null;
    }
  }

  return (
    <GridLayout>
      <div>
        <ExpansionPanel>
          <div className="breadcrumb">
            <NetPyNENewPlot handleClick={handleNewPlot} />
          </div>
          <Box p={1}>
            <RulePath
              style={{ paddingBottom: 8 }}
              text={`simConfig.analysis["${state.selectedPlot}"]`}
            />
            <Box mb={1} />
          </Box>
        </ExpansionPanel>
      </div>
      <Box className="scrollbar scrollchild" mt={1}>
        {plots}
      </Box>
      {selectedPlotComponent}
    </GridLayout>
  );
};

export default NetPyNEPlots;

